from rest_framework import serializers
from django.core.cache import cache
import phonenumbers
from .models import User


class MobileLoginSerializer(serializers.Serializer):
    mobile = serializers.CharField(write_only=True)
    sms = serializers.CharField(write_only=True)

    def validate(self, attrs):
        mobile = attrs.get('phone')
        sms = attrs.get('sms')
        # 从数据库中获取存储的验证码, 检查存储的验证码与输入的验证码是否匹配
        if cache.get(mobile, False):
            stored_sms = cache.get(mobile)
        else:
            attrs['error_message'] = "No verification code found"
            return attrs
        if mobile and sms:
            if str(stored_sms) != str(sms):
                attrs['error_message'] = "Verification code error, sms:{}, stored_sms: {}".format(sms, stored_sms)
                return attrs
            user = User.objects.get(phone_number=mobile)

            if not user:
                attrs['error_message'] = "Access denied: wrong phone number: {mobile} or sms: {sms}."
                return attrs
        else:
            attrs['error_message'] = 'Both "phone number" and "sms" are required.'
            return attrs
        attrs['user'] = user
        return attrs


class SendSMSCodeSerializer(serializers.Serializer):
    mobile = serializers.CharField(write_only=True)

    def validate(self, attrs):
        mobile = attrs.get('phone')
        mobile_string = phonenumbers.parse('+86{}'.format(mobile), None)
        if not phonenumbers.is_valid_number(mobile_string):
            attrs['error_message'] = 'Phone number does not exist: {}'.format(mobile)
            return attrs

        if mobile:
            try:
                user = User.objects.get(phone_number=mobile)
            except:
                attrs['error_message'] = "The number does not exist. No registered user related to the number was found"
                return attrs
        else:
            attrs['error_message'] = 'Phone number error, please re-enter'
            return attrs

        return attrs